package com.fishery.customization.service.impl;

import com.fishery.customization.dao.FixedLabelDao;
import com.fishery.customization.entity.ConstantValue;
import com.fishery.customization.entity.FixedLabel;
import com.fishery.customization.entity.OneLevelLabel;
import com.fishery.customization.service.FixedLabelService;
import com.fishery.customization.util.DataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FixedLabelServiceImpl implements FixedLabelService {

	@Autowired
	private FixedLabelDao fixedLabelDao;

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public List<FixedLabel> findAllFixedLabels() {
		return fixedLabelDao.findAll();
	}

	@Override
	public List<OneLevelLabel> findAllFixedLabels(List<String> types) {
		// 查询固定的标签，先从redis查找
		List<OneLevelLabel> fixedLabels = (List<OneLevelLabel>) redisTemplate.opsForHash()
				.get(ConstantValue.REDIS_FIEXED_LABEL, DataUtil.getRedisKey(types));
		// 发现redis中没有
		if (fixedLabels == null || fixedLabels.isEmpty()) {
			// 从mongo中查找
			fixedLabels = fixedLabelDao.findFixedLabelsByTypes(types);
			// 并将结果保存到redis
			redisTemplate.opsForHash().put(ConstantValue.REDIS_FIEXED_LABEL, DataUtil.getRedisKey(types), fixedLabels);
		}
		return fixedLabels;
	}

	@Override
	public boolean removeFixedLabelById(String id) {
		// 需要重新更新redis
		redisTemplate.delete(ConstantValue.REDIS_FIEXED_LABEL);
		return fixedLabelDao.deleteById(id) > 0;
	}

	@Override
	public boolean saveFixedLabel(FixedLabel fixedLabel) {
		return fixedLabelDao.insert(fixedLabel) > 0;
	}

	@Override
	public boolean updateFixedLabelById(FixedLabel fixedLabel) {
		if (fixedLabel.getLabels() != null || !fixedLabel.getLabels().isEmpty()) {
			// 需要重新更新redis
			redisTemplate.delete(ConstantValue.REDIS_FIEXED_LABEL);
		}
		return fixedLabelDao.updateById(fixedLabel) > 0;
	}

	@Override
	public FixedLabel findFixedLabelById(String type) {
		return fixedLabelDao.findById(type);
	}

	@Override
	public List<String> getAllTypesOfBase() {
		return fixedLabelDao.findAllTypesJsonOfBase();
	}


}
